<?php
	class imageupload
	{
		public $max_image_height;
		public $max_image_width;
		public $max_image_size;
		public $target_directory;
		public $image_extensions;
		public $encode_filename;
		public $prefix;
		public $error_message;
		
		function imageupload(){
			$this->image_extensions = array('jpg', 'jpeg', 'png');
			$this->max_image_height = 1000;
			$this->max_image_width = 1000;
			$this->max_image_size = 1000000;
			$this->encode_filename = true;			
		}		
		
		public function upload($file)
		{		
			// make new name of file
			$new_file = '';
			if ($this->encode_filename)			
				$new_file = $this->encode_filename($file['name']);			
			else
				$new_file = $file['name'];

			$tempFile = $file['tmp_name'];
			$targetPath = $this->target_directory;
			$targetFile = rtrim($targetPath,'/') . '/' . $new_file;		
		
			list($width, $height, $type, $attr) = getimagesize($tempFile);
	
			if (($width > $this->max_image_width) && ($height > $this->max_image_height)) // check width & height
				$this->error_message = 'ขนาดรูปภาพไม่ควรเกิน ' . $this->max_image_width . 'x' . $this->max_image_height;
			else
			{
				if (filesize($tempFile) > $this->max_image_size) // check size
					$this->error_message = 'ขนาดไฟล์รูปภาพไม่ควรเกิน ' . ($this->max_image_size / 1000) . 'kb';
				else
				{				
					$img_path = pathinfo($file['name']);	
					if (!in_array($img_path['extension'], $this->image_extensions)) // check extension
					{
						$txt = 'ไฟล์รูปภาพควรใช้นามสกุล ';
						for ($i=0; $i<count($this->image_extensions); $i++)
							$txt .= $this->image_extensions[$i] . ',';
							
						$this->error_message = $txt;
					}
					else
					{
						move_uploaded_file($tempFile, $targetFile);
						return true;
					}					
				}
			}
			
			return false;
		}
		public function encode_filename($filename)
		{
			$date = date('Ymd');
			$time = date('His');			
			
			$file_ext = explode('.', $filename);
			$new_file = $this->prefix . '_' . $date . '_' . $time . '_' . $filename;
			
			return $new_file;
		}
		
	}
?>